package web.weibo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import web.weibo.mapper.MapperUser;
import web.weibo.model.Message;
import web.weibo.model.User;
import web.weibo.service.ServiceMessage;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Controller
public class ControllerMessage {

    private MapperUser mapperUser;
    private ServiceMessage serviceMessage;

    ControllerMessage(MapperUser mapperUser, ServiceMessage serviceMessage) {
        this.mapperUser = mapperUser;
        this.serviceMessage = serviceMessage;
    }

    @GetMapping("/message")
    public ModelAndView all(HttpServletRequest request) {
        // 显示当前用户所有 message
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        int user_id = currentUser.id;
        ArrayList<Message> messages = this.serviceMessage.currentUserMessages(currentUser);
        // // 读出 模板 文件并把数据放进 html 文件
        ModelAndView modelAndView = new ModelAndView("message");
        modelAndView.addObject("messages", messages);
        modelAndView.addObject("user_id", user_id);
        return modelAndView;
    }

    @GetMapping("/message/get")
    public ModelAndView addGet(HttpServletRequest request, String content) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceMessage.addGet(content, currentUser);
        return new ModelAndView("redirect:/message");
    }

    @PostMapping("/message/post")
    public ModelAndView addPost(HttpServletRequest request, String content) {
        User currentUser = ControllerHelper.currentUser(this.mapperUser, request);
        this.serviceMessage.addPost(content, currentUser);
        return new ModelAndView("redirect:/message");
    }
}
